package com.koron.housing.info.controller;


import cn.hutool.poi.excel.WorkbookUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.github.pagehelper.PageInfo;
import com.koron.bean.base.Response;
import com.koron.bean.query.PageQuery;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.housing.info.bean.dto.HousingInfoDTO;
import com.koron.housing.info.bean.dto.HousingInfoExcel;
import com.koron.housing.info.bean.dto.HousingInfoTree;
import com.koron.housing.info.bean.po.HousingInfo;
import com.koron.housing.info.bean.query.HousingInfoQuery;
import com.koron.housing.info.bean.vo.HousingInfoVO;
import com.koron.housing.info.excel.HousingInfoImportListener;
import com.koron.housing.info.service.HousingInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.Workbook;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

/**
 * 房源台账(HousingInfo)表控制层
 *
 * @author jzp
 * @since 2022-02-25 15:16:32
 */
@Api(tags = "房源台账接口")
@RestController
@RequestMapping("housingInfo")
public class HousingInfoController {
    /**
     * 服务对象
     */
    @Autowired
    private HousingInfoService housingInfoService;

    private String getCurrDs() {
        return ThreadLocalContext.get().getCurrDs();
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation(value = "根据id查询")
    @GetMapping
    public Response<HousingInfo> selectOne(@RequestParam String id) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), housingInfoService, "getById", HousingInfo.class, id));
    }

    @ApiOperation(value = "分页查询")
    @GetMapping("page")
    public Response<PageInfo<HousingInfoVO>> page(PageQuery pageQuery, HousingInfoQuery query) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), housingInfoService, "page", PageInfo.class, pageQuery, query));
    }

    @ApiOperation(value = "台账树查询")
    @GetMapping("tree")
    public Response<List<HousingInfoTree>> tree() {
        return Response.ok(ADOConnection.runTask(getCurrDs(), housingInfoService, "tree", List.class));
    }

    @ApiOperation(value = "地址或小区集合查询", notes = "第一个为地址，第二个为小区")
    @GetMapping("village")
    public Response<List<List<HousingInfo>>> village(String propertySource) {
        return Response.ok(Arrays.asList(
                ADOConnection.runTask(getCurrDs(), housingInfoService, "address", List.class, propertySource),
                ADOConnection.runTask(getCurrDs(), housingInfoService, "village", List.class, propertySource)
        ));
    }

    @ApiOperation(value = "是否有过期房源", notes = "第一个为框架合同，第二个为租赁合同")
    @GetMapping("expired")
    public Response<List<Boolean>> expired() {
        return Response.ok(ADOConnection.runTask(getCurrDs(), housingInfoService, "hasExpiredHouse", List.class));
    }

    @ApiOperation(value = "获取房源通知信息")
    @GetMapping("topic")
    public Response<String> topic() {
        return Response.ok(ADOConnection.runTask(getCurrDs(), housingInfoService, "topic", String.class));
    }

    @ApiOperation(value = "发送房源通知")
    @GetMapping("sendMessage")
    public Response sendMessage(String message) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), housingInfoService, "sendMessage", String.class, message));
    }

    @ApiOperation(value = "保存或更新")
    @PostMapping("save")
    public Response<String> save(@RequestBody HousingInfo housingInfo) {
        ADOConnection.runTask(getCurrDs(), housingInfoService, "save", Boolean.class, housingInfo);
        return Response.ok(housingInfo.getId());
    }

    @ApiOperation(value = "状态变更")
    @PutMapping("updateStatus")
    public Response<String> updateStatus(@RequestParam String id, @RequestParam String status) {
        ADOConnection.runTask(getCurrDs(), housingInfoService, "updateStatus", Boolean.class, id, status);
        return Response.ok();
    }

    @ApiOperation(value = "删除数据")
    @DeleteMapping
    public Response<String> delete(@RequestParam String id) {
        ADOConnection.runTask(getCurrDs(), housingInfoService, "deleteById", Boolean.class, id);
        return Response.ok();
    }

    @SneakyThrows
    @ApiOperation(value = "导出")
    @GetMapping("export")
    public void exportFile(HttpServletResponse response, HousingInfoQuery query) {
        List<HousingInfoVO> list = ADOConnection.runTask(getCurrDs(), housingInfoService, "listVo", List.class, query);

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("房源信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), HousingInfoDTO.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .sheet("房源信息")
                .doWrite(list);
    }

    @SneakyThrows
    @ApiOperation(value = "下载模板")
    @GetMapping("template")
    public void template(HttpServletResponse response) {
        String path = "excel/housing_info_export.xlsx";
        ClassPathResource classPathResource = new ClassPathResource(path);
        Workbook book = WorkbookUtil.createBook(classPathResource.getInputStream());
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("房源信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        book.write(response.getOutputStream());
    }

    @SneakyThrows
    @ApiOperation(value = "导入")
    @PostMapping("import")
    public Response importFile(@RequestParam("file") MultipartFile file) {
        EasyExcel.read(file.getInputStream(), HousingInfoExcel.class, new HousingInfoImportListener(housingInfoService))
                .sheet("房源信息")
                .doRead();

        return Response.ok("导入成功", null);
    }

}
